package com.cxyd.utils;

public class DataUtils {

    public static String str2Hex(String addr) {
        //将字符转换为int
        int num = Integer.parseInt(addr);
        String hexStr = String.format("%04X", num);
        String frontNum = hexStr.substring(0, 2);
        String afterNum = hexStr.substring(2, 4);
        return afterNum + frontNum;
    }

    public static String str2str(String fromStr) {
        String frontStr = fromStr.substring(0, 2);
        String afterStr = fromStr.substring(2, 4);
        return afterStr + frontStr;
    }

    /**
     * 字节逆转如00 01->01 00
     */
    public static byte[] byteResolve(byte[] bytes) {
        if (bytes != null && bytes.length > 0) {
            byte[] newByte = bytes.clone();
            for (int i = 0; i < bytes.length; i++) {
                newByte[i] = bytes[bytes.length - i - 1];
            }
            return newByte;
        }
        return null;
    }

    /**
     * 将整数值转为字节数组
     */
    public static byte[] byteResolve(long value, int byteLength) {
        byte[] bytes = new byte[byteLength];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) ((value >> (8 * (byteLength - 1 - i))) & 0xff);
        }
        return byteResolve(bytes);
    }

    public static String byteToStr(byte[] writeData) {
        if (writeData == null) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder("[");
        for (byte writeDatum : writeData) {
            stringBuilder.append(Integer.toHexString(writeDatum & 0xff));
            stringBuilder.append(",");
        }
        stringBuilder.append("]");
        return stringBuilder.toString();
    }

    public static String arrayToStr(Object[] data) {
        if (data == null) {
            return "null";
        }
        StringBuilder stringBuilder = new StringBuilder("[");
        for (int i = 0; i < data.length; i++) {
            stringBuilder.append(data[i]);
            if (i != data.length - 1) {
                stringBuilder.append(",");
            }
        }
        stringBuilder.append("]");
        return stringBuilder.toString();
    }
}
